package org.androidpush.activity;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.ConnectivityManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.RadioButton;
import android.widget.RadioGroup;

import com.squareup.okhttp.Call;
import com.squareup.okhttp.Callback;
import com.squareup.okhttp.FormEncodingBuilder;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.Response;

import org.androidpush.R;
import org.androidpush.client.Constants;
import org.androidpush.client.LogUtil;
import org.androidpush.greendao.Student;
import org.androidpush.greendao.StudentDao;
import org.androidpush.utils.ConstantUtils;
import org.androidpush.utils.DBUtils;

import java.io.IOException;

public class LoginActivity extends Activity {

    private static final String LOGTAG = LogUtil
            .makeLogTag(LoginActivity.class);

    private String url = ConstantUtils.URL;
    private EditText txUerid = null,txPassword = null;
    private ImageButton btnLogin = null;
    private RadioGroup statusRadio = null;
    private RadioButton stuRadio = null, teaRadio = null, admRadio;
    private String userId = null, userPwd = null, status = ConstantUtils.STUDENT;
    private static final int MSG_SUCCESS = 0;
    private static final int MSG_FAILURE = 1;
    private static final int MSG_ERRORRE = 2;
    private SharedPreferences sp;
    private SharedPreferences.Editor editor;
    private StudentDao studentDao;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.xml_login);
        sp = LoginActivity.this.getSharedPreferences(Constants.SHARED_PREFERENCE_NAME, MODE_PRIVATE);
        editor = sp.edit();

        initView();
        setListener();
    }
    /**
     * 控件初始化
     */
    private void initView() {
        btnLogin = (ImageButton) findViewById(R.id.Id_Login_Ib);
        txUerid = (EditText) findViewById(R.id.Id_Userid_Et);
        txPassword = (EditText) findViewById(R.id.Id_Password_Et);
        statusRadio = (RadioGroup) findViewById(R.id.Id_Status_Rg);
        stuRadio = (RadioButton) findViewById(R.id.Id_Student_Rb);
        teaRadio = (RadioButton) findViewById(R.id.Id_Teacher_Rb);
        admRadio = (RadioButton) findViewById(R.id.Id_Admin_Rb);
        studentDao = DBUtils.getStudentDao(LoginActivity.this);
    }
    /**
     * 监听登录按钮Button和身份单选框Radio
     */
    private void setListener() {
        statusRadio.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                if (checkedId == stuRadio.getId()) {
                    status = ConstantUtils.STUDENT;
                } else if (checkedId == teaRadio.getId()) {
                    status = ConstantUtils.TEACHER;
                } else if (checkedId == admRadio.getId()) {
                    status = ConstantUtils.ADMIN;
                }
            }
        });
        btnLogin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                editor.putString(ConstantUtils.USER_ID, userId)
                        .putString(ConstantUtils.PASSWORD, userId)
                        .putString(ConstantUtils.STATUS, ConstantUtils.STUDENT);
                editor.commit();
                String url = ConstantUtils.URL + "JxhtWeb/StudentController/" + userId + "/getStudentInfoSiglne";
                Log.d(LOGTAG, url);
                new MeInfoAsyncTask().execute(url);


                userId = txUerid.getText().toString();
                userPwd = txPassword.getText().toString();
                url = ConstantUtils.URL + "JxhtWeb/LoginController/" + userId + "/Login";
                if (checkNull()) {
                        try {
                            loginService(url);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                } else {
                    ConstantUtils.logToast(LoginActivity.this, getResources().getString(R.string.str_id_notnull));
                }
            }
        });
    }
    /**
     * 请求服务端进行身份验证
     *
     * @param url
     * @throws Exception
     */
    public void loginService(final String url) throws Exception {
        new Thread(new Runnable() {
            @Override
            public void run() {
                OkHttpClient okHttpClient = new OkHttpClient();
                FormEncodingBuilder builder = new FormEncodingBuilder();
                builder.add("userId", userId)
                        .add("userPwd", userPwd)
                        .add("status", status);
                Request request = new Request.Builder().post(builder.build()).url(url).build();
                Call call = okHttpClient.newCall(request);
                call.enqueue(new Callback() {
                    /**
                     * 访问服务端失败后执行
                     * @param request
                     * @param e
                     */
                    @Override
                    public void onFailure(Request request, IOException e) {
                        e.printStackTrace();
                    }
                    /**
                     * 访问服务端成功后执行
                     * @param response
                     * @throws IOException
                     */
                    @Override
                    public void onResponse(Response response) throws IOException {
                        String result = (String) response.body().string();
                        Log.d("onResponse", result);
                        if ("SUCCESS".equals(result)) {
                            mhandler.obtainMessage(MSG_SUCCESS).sendToTarget();
                            return;
                        } else if ("FAIL".equals(result)) {
                            mhandler.obtainMessage(MSG_FAILURE).sendToTarget();
                            return;
                        } else {
                            mhandler.obtainMessage(MSG_ERRORRE).sendToTarget();
                            return;
                        }
                    }
                });
            }
        }).start();
    }
    /**
     * Handler线程更新提示错误
     */
    private Handler mhandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case MSG_SUCCESS: {
                    successLogin();
                    break;
                }
                case MSG_FAILURE: {
                    ConstantUtils.logToast(LoginActivity.this, getResources().getString(R.string.str_login_faile));
                    break;
                }
                case MSG_ERRORRE: {
                    ConstantUtils.logToast(LoginActivity.this, getResources().getString(R.string.str_login_error));
                }
            }
        }
    };
    /**
     * 成功验证后跳转到主界面
     */
    public void successLogin() {

        editor.putString(ConstantUtils.USER_ID, userId)
                .putString(ConstantUtils.PASSWORD, userPwd)
                .putString(ConstantUtils.STATUS, status);
        editor.commit();
        String url = ConstantUtils.URL + "JxhtWeb/StudentController/" + userId + "/getStudentInfoSingle";
        Log.d("URL", url);
        new MeInfoAsyncTask().execute(url);
        Intent intent = new Intent();
        intent.setClass(LoginActivity.this, MainActivity.class);
        startActivity(intent);
        LoginActivity.this.finish();
    }
    /**
     * 判断输入账号和密码是否为空
     * @return
     */
    public Boolean checkNull() {
        if (null == userId || "".equals(userId)) {
            return false;
        }
        if (null == userPwd || "".equals(userPwd))
            return false;
        return true;
    }

    class MeInfoAsyncTask extends
            AsyncTask<String, Void, String> {

        @Override
        protected String doInBackground(String... params) {
            return ConstantUtils.getDateFrom(params[0]);
        }

        @Override
        protected void onPostExecute(String result) {
            super.onPostExecute(result);

            if(ConstantUtils.NET_ERROR.equals(result)){
                Log.d(LOGTAG, result);
                ConstantUtils.logToast(LoginActivity.this,"发错误");
            }else {
                Student student = ConstantUtils.parseJsonWithGson(result, Student.class);
                studentDao.insertOrReplace(student);
            }
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        DBUtils.closeDB();
    }
}